﻿using CRM.Infrastructure.Entity;
using CRM.Infrastructure.Models;
using CRM.Infrastructure.Service;
using CRM.Op.Common;
using CRM.Utility;
using Dapper.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CRM.Op.Controllers
{
    public class UserController : BaseController
    {
        UsersService _service = new UsersService();

        #region 普通用户

        // GET: User
        public ActionResult UserList()
        {
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ContentResult GetUserList(UserSearchModel model)
        {
            model.CompanyID = CurrentUser.CompanyID;
            Page<Users> page = _service.Pages(model.PageIndex, model.PageSize, model);
            return ReturnResult(page);
        }
        #endregion

        #region 管理员帐号
        public ActionResult AdminUserList()
        {
            return View();
        }

        [HttpPost]
        public ContentResult GetAdminUserList(UserSearchModel model)
        {
            model.RoleID = 1;
            model.CompanyID = -1;
            Page<Users> page = _service.Pages(model.PageIndex, model.PageSize, model);
            return ReturnResult(page);
        }
        #endregion

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult EditPwd(UserPassword model)
        {
            ResultData<int> rt = ResultData<int>.Error("");

            if (model.UserID <= 0)
            {
                rt.message = "缺少必须的参数UserID";
                return ReturnResult(rt);
            }

            if (string.IsNullOrWhiteSpace(model.Pwd))
            {
                rt.message = "请输入新密码";
                return ReturnResult(rt);
            }

            var entity = _service.Single(model.UserID);
            if (entity != null)
            {
                entity.PassWord = MD5Helper.MD5String(entity.UserName + model.Pwd + "!!!");
                entity.UpdatedDate = DateTime.Now;
                var re = _service.Update(entity);
                if (re)
                {
                    rt.message = "更新成功";
                    rt.status = 0;
                }
                else
                {
                    rt.message = "更新失败";
                }
            }
            else
            {
                rt.message = "未找到用户，检查UserID是否正确";
            }
            return ReturnResult(rt);
        }

        /// <summary>
        /// 停用启用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult SetStopStatus(Users model)
        {
            ResultData<int> rt = ResultData<int>.Error("");

            if (model.UserID <= 0)
            {
                rt.message = "缺少必须的参数UserID";
                return ReturnResult(rt);
            }
            var entity = _service.Single(model.UserID);
            if (entity == null)
            {
                rt.message = "未找到用户，检查UserID是否正确";
                return ReturnResult(rt);
            }


            if (entity.RoleID == 1)
            {
                rt.message = "管理员不能停用";
                return ReturnResult(rt);
            }

            entity.IsStop = model.IsStop;
            entity.UpdatedDate = DateTime.Now;
            var re = _service.Update(entity);
            if (re)
            {
                rt.message = "更新成功";
                rt.status = 0;
            }
            else
            {
                rt.message = "更新失败";
            }

            return ReturnResult(rt);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ContentResult Delete(long userId)
        {
            var entity = _service.SingleOrDefault(userId);
            if (entity.RoleID == 1)
            {
                return ReturnResult(ResultData<string>.Error("管理员不能删除"));
            }
            entity.UpdatedDate = DateTime.Now;
            entity.IsActive = 0;
            _service.Update(entity);
            return ReturnResult(ResultData<string>.Success("删除成功"));
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Add()
        {
            //超级管理员添加时RoleID=1，普通管理员添加时RoleID=2
            Users model = new Users()
            {
                PassWord = "123456",
                RoleID = 1
            };
            if (CurrentUser.RoleID == 1)
            {
                model.RoleID = 2;
            }
            var userId = GetParam<int>("userId");
            if (userId > 0)
            {
                model = _service.Single(userId);
                if (model == null)
                    model = new Users();
            }
            return View(model);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="usr"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Add(Users usr)
        {
            if (usr.UserID > 0)
            {
                var entity = _service.Single(usr.UserID);
                if (entity == null)
                {
                    return ReturnResult(ResultData<string>.Error("保存失败，用户不存在"));
                }

                entity.UserName = usr.UserName;
                entity.PassWord = MD5Helper.MD5String(usr.UserName + usr.PassWord + "!!!");
                entity.Mobile = usr.Mobile;
                //如果是管理员编辑页面，则更新公司信息
                if (usr.RoleID > 0 && usr.CompanyID > 0)
                {
                    entity.CompanyID = usr.CompanyID;
                    entity.CompanyName = usr.CompanyName;
                }
                _service.Update(entity);
            }
            else
            {
                var user = _service.GetByLoginNum(usr.UserName);
                if (user != null)
                {
                    return ReturnResult(ResultData<string>.Error("添加失败，用户已存在，请更换用户名"));
                }
                usr.IsActive = 1;
                usr.IsStop = 0;
                usr.CreatedDate = DateTime.Now;
                if (usr.RoleID == 2)
                {
                    //非管理员编辑页面，则添加用户都是默认当前公司
                    usr.CompanyID = CurrentUser.CompanyID;
                    usr.CompanyName = CurrentUser.CompanyName;
                }
                else
                {
                    var usrs = _service.GetByCompany(usr.CompanyID);
                    if (usrs.Count > 0)
                    {
                        return ReturnResult(ResultData<string>.Error("添加失败，公司已经存在，请更换公司ID"));
                    }
                }
                usr.UpdatedDate = DateTime.Now;
                usr.PassWord = MD5Helper.MD5String(usr.UserName + usr.PassWord + "!!!");
                _service.Insert(usr);
            }
            return ReturnResult(ResultData<string>.Success("保存成功"));
        }

    }
}